//引入路由配置文件
import router from "@/router";
import axios from "axios";
// import { Message } from "element-ui";
import qstring from "querystring"

// 
let baseurl = "/api"

//拦截器
// 请求拦截
axios.interceptors.request.use((req) => {

    if (req.url == "/api/userlogin") {
        return req
    } else {
        // 全局添加请求头
        req.headers.authorization = sessionStorage.getItem("userInfo") ? JSON.parse(sessionStorage.getItem("userInfo")).token : null
        return req
    }

})
// 响应拦截
axios.interceptors.response.use((res) => {
    // 全局拦截错误
    if (res.data.msg == "请设置请求头,并携带验证字符串") {
        // 没有请求头强制返回登录页
        router.push('/login')
    }
    // 登录token过期返回登录
    if (res.data.msg == "登录已过期或访问权限受限") {
        router.push('/login')
    }
    return res.data

})

//get
export const get = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        axios.get(baseurl + url, {
            params
        })
            .then(res => resolve(res))
            .catch(err => reject(err))
    })
}

//post
export const post = (url, params = {}, isFile = false) => {
    //
    let data = null
    if (isFile) {
        data = new FormData()
        for (let i in params) {
            data.append(i, params[i])
        }
    } else {
        data = qstring.stringify(params)
    }
    return new Promise((resolve, reject) => {
        axios.post(baseurl + url, data)
            .then(res => resolve(res))
            .catch(err => reject(err))
    })
}